package com.achao.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Author: achao
 * @DateTime: 2022/7/24 1:00
 * @Description: TODO
 */
public class MybatisUtils {

    private static SqlSessionFactory sqlSessionFactory;
    private static SqlSession sqlSession;

    static {
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream;
            inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // sqlSessionFactory---> sqlSession  Factory构建SqlSession
    public static SqlSession getSqlSession() {
        sqlSession = sqlSessionFactory.openSession(false);
        return sqlSession;
    }

    // 关闭连接
    public static void closeSession() {
        sqlSession.commit();
        sqlSession.close();
    }

}
